const https = require('https');
let SQLhelper = require('./SQLhelper');
const snowflake = require('./snowflake');
let tokens = {}
// const {JSON}= require('mysql/lib/protocol/constants/types');
// SQLhelper(`select * from  member`).then(res => {
//     console.log("i am mysql", res);
// })

module.exports = function (app) {
    //登录拦截中间件
    function loginRouter(req, res, next) {
        let token = req.headers.token
        console.log("token", token);
        if (token) {
            SQLhelper(`select * from session where id=${token} and state=1`).then(ret => {
                if (ret.length) {
                    let session = ret[0]
                    if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
                        req.session = {
                            userId: session.userId,
                            userName: session.userName
                        }
                        next()
                    } else {
                        res.status(400).send({
                            errMsg: '登录超时'
                        })
                    }
                } else {
                    res.status(406).send({
                        errMsg: '当前用户未登陆'
                    })
                }
            })
        } else {
            res.status(405).send({
                errMsg: '缺少token，请先进行登录'
            })
        }
    }

    //日期格式化
    const formatTime = date => {
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()

        return `${[year,month,day].map(formatNumber).join('/')} ${[hour,minute,second].map(formatNumber).join(':')}`
    }
    const formatNumber = n => {
        n = n.toString()
        return n[1] ? n : `0${n}`
    }
    // app.get('/wx/login',(req,res)=>{
    //     console.log(req.headers);
    //     let code=req.query.code
    //      let appid = 'wx2bd09bfc743d6085'
    //      let secret = '8cfa0c788ddff119408acff770d9509d'
    //      https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {  
    //                  ret.on('data', (d) => {
    //                      res.send(d.toString())
    //                  });

    //              }).on('error', (e) => {
    //                  console.error(e);
    //              });
    // })


    app.use('/admin', loginRouter)
    //微信登录
    // app.listen(port, () => {
    //     console.log(`Example app Listening on port ${port}`);
    // })
    // app.use(express.static('www'))
    // app.listen(port, () => {
    //     console.log(`Example app Listening on port ${port}`);
    // })
    // app.use(express.static('www'))

    //管理后台登陆
    app.post('/login', (req, res) => {
        // console.log("req.body",req);
        let userName = req.body.userName
        let passWord = req.body.passWord
        if (userName && passWord) {
            SQLhelper(`select* from user where userName='${userName}'`).then(users => {
                if (users.length) {
                    let user = users[0]
                    if (passWord == user.passWord) {
                        let token = snowflake()
                        SQLhelper(`
    INSERT INTO session(id,userId,userName,inTime,createTime,platform) 
    VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}','${new Date().getTime()}','admin')
    `).then(ret => {
                            res.send({
                                nickName: user.nickName,
                                token,
                                avatarUrl: user.photo,
                                _id: user._id
                            })
                        })
                    } else {
                        res.send({
                            errorMsg: "密码错误"
                        })
                    }
                } else {
                    res.send({
                        errorMsg: "当前用户不存在"
                    })
                }
            })
        } else {
            res.send({
                errorMsg: "用户名密码不能为空"
            })
        }
    })

    //退出登录
    app.get('/admin/login', (req, res) => {
        SQLhelper(`
        update session set outTime = '${formatTime(new Date())}',state = 0 where id = '${req.headers.token}'
    `).then(ret => {
            res.send({
                msg: '退出登录成功'
            })
        })
    })

    //修改密码
app.post('/admin/changePassWord',(req,res) => {
    console.log("asda",req.body);
      let userId = req.session.userId
      let passWord = req.body.passWord
      let newPassWord = req.body.NewpassWord
      if(passWord && newPassWord){
        ///查询用户
        SQLhelper(`select passWord from user where _id = ${userId}`).then(users => {
          let user = users[0]
          ///比对原密码
          if(user.passWord == passWord){
            //修改原密码
            SQLhelper(`update user set passWord = '${newPassWord}' where _id = ${userId}`).then(ret => {
              res.send({msg:'修改密码成功'})
            })
          }else{
            res.send({errorMsg:'原密码错误'})
          }
        })
      }else{
        res.send({errorMsg:'原密码和新密码不能为空'})
      }
    }) 

    //获取首页轮播图列表
    //pagesize默认为10
    //pageNUM 当前页为1
    app.get('/admin/index',(req,res)=>{
        let pageSize=req.query.pageSize||10
        let pageNum=req.query.pageNum || 1
        let offset =(pageNum-1)*pageSize
        let title=req.query.title
        let type=req.query.type
        let whereSql='from index_region where state=1'
        if(type){
            whereSql+=` and type ='${type}'`
        }
        //按标题搜索
        if(title)
        whereSql+=` and title like"${title}%"`
        SQLhelper(`select count(*) as total ${whereSql};select *${whereSql} limit ${pageSize} offset ${offset}`).then(ret=>{
            // console.log(ret[0][0].total);
            res.send({
                    ret,
                    total:ret[0][0].total,
                    rows:ret[1]
            })
        })
    })

    // 新增轮播图
    app.post('/admin/index', (req, res) => {
        // console.log("sada", req.body.memberId);
        let img=req.body.img
        let url=req.body.url
        let status=req.body.status
        let type=req.body.type||'banner'
        let title=req.body.title
        if(type != "banner" && !title){
            res.send({errorMsg:"标题不能为空"})
            return
        }
        if(status===undefined){
            status=1
        }
        if (img) {
            let createTime=new Date().getTime()
            SQLhelper(`insert into index_region(title,img,url,status,state,createTime,type) values('banner','${img}','${url}','${status}'
             ,'1','${createTime}','${type}')`)
                .then(ret => {
                    res.send(
                        ret.insertId ?{_id:ret.insertId}:{errorMsg:'新增数据失败'}
                    )
                })
        } else {
            res.send({
                errorMsg: '传入参数错误'
            })
        }
    })

     //修改首页
   ///修改首页项目
    ///indexId 主码_id 必填
    app.put('/admin/index',(req,res) => {
        if(req.body.indexId){
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img','url','title','status']
            let updateValues = [`updateTime=${updateTime}`]
            for(let i = 0; i < updateKey.length; i ++){
                let key = updateKey[i],value = req.body[key]
                if(value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLhelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })

    //删除地址
    app.delete('/admin/index', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLhelper(`update index_region
            set state=0
            where _id=${indexId}`)
                .then(ret => {
                    res.send(ret)
                })
        } else {
            res.send({
                errorMsg: "参数错误"
            })
        }

    })

        //获取商品分类
    app.get('/admin/goods_cate',(req,res)=>{
        let goods=[]
        SQLhelper(`select *from category`).then(ret=>{
            console.log(ret);
            res.send({
                goods:ret
            })
        })
    })
}